import { HttpException, Injectable } from '@nestjs/common';
import { CreateClassificationDto } from './dto/create-classification.dto';
import { UpdateClassificationDto } from './dto/update-classification.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Classification } from './entities/classification.entity';
import { Repository } from 'typeorm';
import { PaginationService } from '../../common/pagination/pagination.service';

@Injectable()
export class ClassificationService {
  constructor(
    @InjectRepository(Classification)
    private readonly calssRepository: Repository<Classification>,
    private pageService: PaginationService<Classification>,
  ) {
    this.pageService = new PaginationService<Classification>(
      this.calssRepository,
    );
  }

  async create(createClassificationDto: CreateClassificationDto) {
    const data = this.calssRepository.create(createClassificationDto);
    return await this.calssRepository.save(data);
  }

  async findAll(params: {
    page: number;
    pageSize: number;
    name: string;
    keywords: string;
    sortFeild: string;
    sort: string;
  }) {
    const { page, pageSize, name, keywords, sortFeild, sort } = params;
    // 定义查询构造器
    const qb = this.calssRepository.createQueryBuilder('classification');
    // 模糊查询name、keywords
    name &&
      qb.andWhere('classification.name like :name', { name: `%${name}%` });
    keywords &&
      qb.andWhere('classification.keywords like :keywords', {
        keywords: `%${keywords}%`,
      });
    // 排序
    if (sortFeild && sort) {
      if(Reflect.ownKeys(new Classification()).includes(sortFeild)) {
        qb.orderBy(
          sortFeild,
          sort.toLocaleUpperCase().startsWith('ASC') ? 'ASC' : 'DESC',
        );
      }else{
        throw new HttpException(`不支持该字段:【${sortFeild}】进行排序`, 400);
      }
    }
    // console.log('pageSearch params', params);
    // 分页查询
    return this.pageService.pageSearch({
      page,
      pageSize,
      queryBuilder: qb,
    });
  }

  // 查询所有分类列表
  async findAllList() {
    return await this.calssRepository.find();
  }

  async findOne(id: string) {
    return await this.calssRepository.findOneBy({ id });
  }

  async update(id: string, updateClassificationDto: UpdateClassificationDto) {
    const data = await this.findOne(id);
    if (!data) throw new HttpException('数据不存在', 400);
    const updateData = this.calssRepository.merge(
      data,
      updateClassificationDto,
    );
    return await this.calssRepository.save(updateData);
  }

  async remove(id: string) {
    const data = await this.findOne(id);
    if (!data) throw new HttpException('数据不存在', 400);
    return await this.calssRepository.delete({ id });
  }
}
